package com.bdqn.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.file.FileWriter;
import com.alibaba.fastjson.JSONObject;
import com.bdqn.pojo.Grade;
import com.bdqn.pojo.User;
import com.bdqn.service.GradeService;
import com.bdqn.service.UserService;
import com.bdqn.util.LayData;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

/**
 * <Description> <br>
 *
 * @author tao<br>
 * @version 1.0<br>
 * @taskId: <br>
 * @createDate 2019/09/16 15:38 <br>
 * @see com.bdqn.controller <br>
 */
@Controller
@RequestMapping("/user")
public class UserController extends BaseController{

    @Resource
    private UserService userService;
    /*1
    */

    /**
     * 1.请求 如何走到后台
     * 2.参数如何传递
     * @return
     */

    @RequestMapping(value="/login",method = RequestMethod.POST)
    public String login(User user,Model model){

        User u =  userService.login(user.getUsername(),user.getPassword());
        model.addAttribute("u",u);
        return "jsp/index";
    }

    @RequestMapping(value="/touser",method = RequestMethod.GET)
    public String toUserList(Model model, HttpSession session){
        return "jsp/user/list";
    }

    @RequestMapping(value="/toadd",method = RequestMethod.GET)
    public String toUserAdd(){
        return "jsp/user/add";
    }

    @RequestMapping(value="/list",method = RequestMethod.GET)
    @ResponseBody
    public String getUserList(User user,Model model, HttpSession session, @RequestParam("page") Long from,@RequestParam("limit") Long limit){
        LayData data = userService.getAll(user,from,limit);
        return JSONObject.toJSONString(data);
    }

    @RequestMapping(value="/addSave",method = RequestMethod.POST)
    public String addSave(User user){
       userService.addSave(user);
        return "redirect:touser";
    }

    @RequestMapping(value="/upload")
    @ResponseBody
    public String upload(@RequestParam("file")MultipartFile file) throws Exception{
        FileUtil.writeBytes(file.getBytes(),"D:/upload/1.png");
        return JSONObject.toJSONString(LayData.data_upload(0L,"上传成功"));
    }

    @RequestMapping(value="/del/{id}")
    @ResponseBody
    public String del(@PathVariable("id") Long id) {
        userService.del(id);
        return JSONObject.toJSONString(LayData.data_upload(0L,"删除成功"));
    }
}
